import {Component, Inject, OnInit, Optional} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {UtilityService} from '../../../../service/utils.service';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import {MenuItem, TreeNode} from 'primeng/api';
import {appConfig} from '../../../../service/common';
import {Observable} from 'rxjs/Observable';
import * as _ from 'lodash';
import {ReuseTabService} from '@delon/abc';
@Component({
    selector: 'app-funcper',
    templateUrl: './funcper.component.html',
})
export class FuncperComponent implements OnInit {
    roleGuid: string;
    treedata: any[]; // tree组件数据
    searchTitle: string; // 树搜索框文字
    treemenus: MenuItem[];
    jurisdictionTree: any[]; // 树节点保存
    checked = false
    // selectionType = 'checkbox'
    selectionType = 'single'
    inputSearch = true;
    isData = true
    noMenu  = true; // 没有右击
    id: any;
    tabShow = false;
    funcInfo: any; // 功能的信息
    isDisabledButton = true; // 默认都是禁选的
    isSaveEdit = true; // 修改和保存二选一按钮, 默认是修改按钮
    roleName: string; // 角色信息
    roleCode: string; // 角色信息
    roleTxt: any[]; // 角色信息
    isrootChild: boolean; // 判断是角色还是角色组
    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数
        private nznot: NzNotificationService,
        private utilityService: UtilityService,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
    ) { }
    checkOptionsOne: any; // 验证行为权限的数组
    nocheckOptionsOne: any; // 不验证行为权限的数组

    ngOnInit() {
        this.roleGuid = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的组织机构的guid来进行操作

        if (this.roleGuid === 'root') {
            this.isrootChild = false;
        } else {
            this.isrootChild = true;
        }
        this.queryRoleData(this.roleGuid);
        this.searchaValue(); // 调用查询接口
        this.initData(); // 初始化树节点

    }


    // 根据guid查询角色消息
    queryRoleData(id) {
        this.utilityService.getData(appConfig.serverUrl +  appConfig.API.queryRoleById + '/' + id)
            .subscribe(
                (val) => {
                    this.roleName = val.result.roleName;
                    this.roleCode = val.result.roleCode;
                    this.reuseTabService.title = this.roleName + '下功能权限'
                });
    }

    initData() {
        this.treedata = [ // 默认根节点
            {
                'label': '应用列表',
                'data': 'default Role',
                'guid': 'appRoot',
                'expandedIcon': '',
                'collapsedIcon': '',
                'children': [{}]
            }
        ];
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.queryAppByRole + '/' + this.roleGuid)
            .subscribe(
                (val) => {
                    for( var i = 0; i < val.result.allData.length; i ++) {
                        val.result.allData[i].label = val.result.allData[i].appName;
                        val.result.allData[i].children = [{}];
                    }
                    this.treedata[0].children = val.result.allData; // 绑定树节点

                });
        this.treedata.forEach( node => {
            this.expandRecursive(node, true);
        });
    }

    // 展开所有树节点的方法
    private expandRecursive(node:TreeNode, isExpand:boolean){
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach( childNode => {
                this.expandRecursive(childNode, isExpand);
            } );
        }
    }

    getQuery(event) {
        if(event.guid !== 'appRoot') {
            let objJson = {
                appId: event.guid,
                roleId: this.roleGuid
            }
            this.utilityService.postData(appConfig.serverUrl +  appConfig.API.queryFuncBehaveByRolApp, objJson)
                .subscribe(
                    (val) => {
                        for(var i = 0; i < val.result.length; i ++) {
                            val.result[i].label = val.result[i].funcName;
                            for(var i = 0; i < val.result.length; i ++) {
                                val.result[i].label = val.result[i].funcName;
                                if (val.result[i].exit === 'true') { // true代表一个行为没有选择，没有配置过行为
                                    // val.result[i].collapsedIcon = 'fa fa-close';
                                } else { // 代表已经有了，那么对勾进行展示
                                    val.result[i].collapsedIcon = 'fa fa-check';
                                }
                            }
                        }
                        event.children = val.result; // 绑定树节点
                    });
            console.log(this.treedata);
        }
    }
    // 点击下拉的方法
    Unfold(event) {
        this.roleTxt = [];
        this.getQuery(event.node)
    }


    // 判断是否全部选中，如果全部选中，那么全选按钮选中，反之 不选中
    checkAdult(age) {
        console.log(age)
        return age.exit === 'false'; // 判断是否全部是false
    }


    // 树节点左击事件
    TreeSelect(event) {
        this.roleTxt = [];
        if (event.node.childs) { // 如果存在，代表功能
            this.tabShow = true;
            this.funcInfo = event.node;
            if(event.node.childs.every(this.checkAdult)) { // 利用every属性，判断是否全部选中，如果全部选中，全选按钮为true
                this.checked = true;
            } else {
                this.checked = false;
            }
            let noArray = []; // 不验证行为数组
            let Array = []; // 验证行为数组
            for(var i = 0 ; i < event.node.childs.length; i ++) {
                event.node.childs[i].label = event.node.childs[i].funcName
                event.node.childs[i].guid = event.node.childs[i].guid;
                if(event.node.childs[i].exit === 'true') { // 如果是true字符串，代表是没有勾选
                    event.node.childs[i].checked = false;
                } else {
                    event.node.childs[i].checked = true;
                }
            }
            Array = _.clone(event.node.childs); // 深拷贝一份
            this.nocheckOptionsOne = _.remove(Array, function(n) { // 不需要验证权限的
                return n.ischeck === '否';
            });
            for(let  s = 0 ; s <　this.nocheckOptionsOne.length; s ++ ) {
                this.nocheckOptionsOne[s].checked = true; // 默认选中
            }
            this.checkOptionsOne = Array; // 需要验证权限的
            this.reset(event.node.childs); // 对所有行为进行修改
        } else {
            this.tabShow = false;
        }
    }


    // 全选按钮
    allSelect($event) {
        this.roleTxt = [];
        if($event) {
            for(let i = 0; i < this.checkOptionsOne.length; i ++) {
                this.checkOptionsOne[i].checked = true;
                this.checkOptionsOne[i].exit = false; // 勾选了
            }
        } else {
            for(let i = 0; i < this.checkOptionsOne.length; i ++) {
                this.checkOptionsOne[i].checked = false;
                this.checkOptionsOne[i].exit = true; // 没有勾选
            }
        }
        this.reset(this.checkOptionsOne);
    }


    reset(checkOptionsOne){
        this.roleTxt = [];
        for(var i = 0 ; i < checkOptionsOne.length; i ++) {
            if (checkOptionsOne[i].checked === true) { // 如果是true字符串，代表是没有勾选
                this.roleTxt.push(checkOptionsOne[i].funcDesc);
            }
        }
    }


    // 树节点搜索框的内容
    searchaValue() {
        const change = document.getElementById( 'searchaVals');
        const change$ = Observable.fromEvent(change, 'keyup').pluck('target', 'value').debounceTime(600);
        change$.subscribe(sussess  => {
            let jsonObj = {
                guid: 'null',
                name: sussess,
                roleId: this.roleGuid
            }
           if(sussess === '') {
                    this.initData();
                    this.tabShow = false;
           } else {
               this.utilityService.postData(appConfig.serverUrl  + appConfig.API.getFilterFuncBehaveByRole, jsonObj)
                   .subscribe(
                       (val) => {
                           this.tabShow = false;
                           if (val.code === '200' || val.code === 200) {
                               this.treedata = [ // 默认根节点
                                   {
                                       'label': '应用列表',
                                       'data': 'default Role',
                                       'guid': 'appRoot',
                                       'expandedIcon': '',
                                       'collapsedIcon': '',
                                       'children': [{}]
                                   }
                               ];
                               this.treedata[0].children = val.result.allData;
                               for(let i = 0; i < val.result.allData.length; i ++) {
                                   console.log(val.result.allData[i]);
                                   val.result.allData[i].label = val.result.allData[i].appName;
                                   if(val.result.allData[i].funcList.length > 0) { // 说明有功能
                                       for(let s = 0; s < val.result.allData[i].funcList.length; s++) {
                                           val.result.allData[i].funcList[s].label = val.result.allData[i].funcList[s].funcName;
                                       }
                                       val.result.allData[i].children = val.result.allData[i].funcList;
                                   }
                               }
                               // 展开所有的
                               this.treedata.forEach( node => {
                                   this.expandRecursive(node, true);
                               } );
                           }
                       },
                   );
           }

        });
    }

    // 修改按钮展现
    edit() {
        this.isSaveEdit = false; // 保存按钮显示,修改按钮隐藏
        this.isDisabledButton = false; // 改成可以修改
    }


    save() {
        this.isSaveEdit = true; // 修改按钮显示,保存按钮隐藏
        this.isDisabledButton = true; // 改成不可以修改
        let array = [];
        let treeArray = this.treedata[0].children;
        for(let i = 0; i < treeArray.length; i++) { // 所有应用
            console.log(treeArray[i])
            for(let j = 0; j < treeArray[i].children.length; j++) { // 所有功能
                if(treeArray[i].children[j].funcCode) {
                    for(let s = 0 ; s < treeArray[i].children[j].childs.length; s ++) {
                        if(treeArray[i].children[j].childs[s].childs === '') {
                            if (treeArray[i].children[j].childs[s].checked || treeArray[i].children[j].childs[s].exit === 'false') {
                                array.push(treeArray[i].children[j].childs[s].guid)
                            }
                        }
                    }
                }
            }
        }
        let objJson = {
            behaveIdList: array,
            roleId: this.roleGuid
        }
        console.log(objJson)
        this.utilityService.postData(appConfig.serverUrl +  appConfig.API.batchAdd, objJson)
            .subscribe(
                (val) => {
                    console.log(val.result)
                    this.nznot.create('success', val.msg , val.msg);
                },
                (error)=> {
                    this.nznot.create('error', error.msg , error.msg);
                });
    }

    cloneArray = [];


    changes(event) {
        if(this.checkOptionsOne.every(item => item.checked ===  true)) { // 利用every属性，判断是否全部选中，如果全部选中，全选按钮为true
            this.checked = true;
        } else {
            this.checked = false;
        }
        event.forEach(item => {
            item.exit = !item.checked + '';
        })
    }

    // 树节点三个按钮方法
    clickFunc($event) {
        if($event === 'reset') {
            this.initData();
            this.tabShow = false;
        } else if($event === 'expand') { // 全部展开方法
            let treeList = this.treedata[0].children
            for( let i = 0; i　< treeList.length; i++) {
                this.getQuery(treeList[i])
            }
            // 展开所有的
            this.treedata.forEach( node => {
                this.expandRecursive(node, true);
            });
        } else { // 收缩
            let treeList = this.treedata[0].children
            for( let i = 0; i　< treeList.length; i++) {
                this.getQuery(treeList[i])
            }
            this.tabShow  = false;
            this.treedata.forEach( node => {
                this.expandRecursive(node, false);
            } );
        }
    }





    cancel() {
        this.isSaveEdit = true; // 保存按钮显示,修改按钮隐藏
        this.isDisabledButton = true; // 改成可以修改
    }
}
